<?php

setlocale(LC_ALL, "ru_RU.UTF-8");
mb_internal_encoding("UTF-8");

$curRealDir = mb_substr($_SERVER["SCRIPT_FILENAME"], 0, mb_strrpos($_SERVER["SCRIPT_FILENAME"], "/"));

require_once ("./config/setup.php");
require_once ("./libs/db.class.php");
require_once ("./libs/utils.inc.php");
require_once ("./libs/ipActivity.inc.php");
$sm = new SSmarty();
$db = new DB();

//--правый блок
//--из админки
$LAST_TAGS_COUNT = getOption($db, "LAST_TAGS_COUNT");
//-------------------

$db->dbq("
            Select
                tags
            From
                news
        ");
$lastTags = array();
while ($arr = $db->row()) {
    $tags = json_decode($arr[0], true);
    foreach ($tags as $key => $tag) {
        if ($tag != "") {
            if (!isset($lastTags[$tag])) {
                $query = preg_split("'
                                        [\ ,.\t\r\n]+
                                    'iusx", $tag);
                $utf8BytesRegexp = array();
                foreach ($query as $key => $value) {
                    $utf8BytesRegexp[] = mb_substr(json_encode($value), 1, mb_strlen(json_encode($value)) - 2);
                }
                $utf8BytesRegexp = implode("(.*)", $utf8BytesRegexp);
                $utf8BytesRegexp = addslashes(addslashes($utf8BytesRegexp));
                $regexp = implode("(.*)", $query);

                $db->dbqi(1, "
                            Select
                                Count(*)
                            From
                                news
                            Where
                                caption Regexp(\"" . $regexp . "\") ||
                                maintext Regexp(\"" . $regexp . "\") ||
                                DATE_FORMAT(postdate, \"%d %M %Y, %H:%i\") Regexp(\"" . $regexp . "\") ||
                                author Regexp(\"" . $regexp . "\") ||
                                tags Regexp(\"" . $utf8BytesRegexp . "\")
                        ");
                $arr = $db->rowi(1);
                $lastTags[$tag] = $arr[0];
            }
        }
    }
}

arsort($lastTags);
$lastTags = array_splice($lastTags, 0, $LAST_TAGS_COUNT);
$sm->assign("lastTags", $lastTags);

//------------------------------------

$newid = trim(mysql_real_escape_string($_GET["newid"]));
if (!preg_match("'^[0-9]+$'iu", $newid) || $newid < 1) {
    $newid = 1;
}
$sm->assign("newid", $newid);

if ($_COOKIE["ok"] != "") {
    setcookie("ok", "", mktime(0, 0, 0, 1, 1, 1902));
    $sm->assign("ok", true);
}
if ($_COOKIE["capcha"] != "") {
    setcookie("capcha", "", mktime(0, 0, 0, 1, 1, 1902));
    $sm->assign("capcha", true);
}

//--из админки
$COMMENTS_IP_PER_HOUR = getOption($db, "COMMENTS_IP_PER_HOUR");
$COMMENTS_MINIMUM_LOGIN_LENGTH = getOption($db, "COMMENTS_MINIMUM_LOGIN_LENGTH");
$COMMENTS_MINIMUM_TEXT_LENGTH = getOption($db, "COMMENTS_MINIMUM_TEXT_LENGTH");
//------------------

$ip = $_SERVER["REMOTE_ADDR"];
if ($_SERVER["HTTP_X_FORWARDED_FOR"] != "") {
    $ip = $_SERVER["HTTP_X_FORWARDED_FOR"];
}

if (ipActivityNormalComment($db, $ip, $COMMENTS_IP_PER_HOUR) == 0) {
    $sm->assign("capcha", true);
}

//--отправка комментария

if (isset($_POST["submit"])) {

    $sm->assign("rand", time());

    $_POST["login"] = trim(htmlspecialchars(mysql_real_escape_string($_POST["login"])));
    $_POST["commentText"] = trim(htmlspecialchars(mysql_real_escape_string($_POST["commentText"])));
    $_POST["capchaText"] = trim(htmlspecialchars(mysql_real_escape_string($_POST["capchaText"])));

    $go = true;
    if (mb_strlen($_POST["login"]) < $COMMENTS_MINIMUM_LOGIN_LENGTH) {
        $go = false;
        $sm->assign("loginTooShort", true);
    }
    if (mb_strlen($_POST["commentText"]) < $COMMENTS_MINIMUM_TEXT_LENGTH) {
        $go = false;
        $sm->assign("textTooShort", true);
    }

    if ($go) {
        switch (ipActivityNormalCommentAdding($db, $ip, $COMMENTS_IP_PER_HOUR)) {
            case 1:
                $db->dbq("
                            Delete
                            From
                                capchas
                            Where
                                UNIX_TIMESTAMP(Now() - capchatake) > 3600
                        ");
                $db->dbq("
                            Insert
                            Into
                                comments
                            Values
                                (
                                    0,
                                    \"" . $_POST["login"] . "\",
                                    \"" . $_POST["commentText"] . "\",
                                    Now(),
                                    \"" . $newid . "\"
                                )
                        ");
                setcookie("ok", true, mktime(0, 0, 0, 1, 1, 2030));
                header("Location: /new" . $newid . ".html/" . $pagenum . "/");
                exit(0);
                break;
            case 0.5:
                $db->dbq("
                            Insert
                            Into
                                comments
                            Values
                                (
                                    0,
                                    \"" . $_POST["login"] . "\",
                                    \"" . $_POST["commentText"] . "\",
                                    Now(),
                                    \"" . $newid . "\"
                                )
                        ");
                setcookie("ok", true, mktime(0, 0, 0, 1, 1, 2030));
                setcookie("capcha", true, mktime(0, 0, 0, 1, 1, 2030));
                header("Location: /new" . $newid . ".html/" . $pagenum . "/");
                exit(0);
                break;
            case 0:
                $db->dbq("
                            Select
                                capchatext
                            From
                                capchas
                            Where
                                ip = \"" . $ip . "\" &&
                                UNIX_TIMESTAMP(Now() - capchatake) < 3600
                        ");
                $arr = $db->row();
                if ($arr[0] == $_POST["capchaText"] && mb_strlen($_POST["capchaText"]) > 0) {
                    $db->dbq("
                                Insert
                                Into
                                    comments
                                Values
                                    (
                                        0,
                                        \"" . $_POST["login"] . "\",
                                        \"" . $_POST["commentText"] . "\",
                                        Now(),
                                        \"" . $newid . "\"
                                    )
                            ");
                    setcookie("ok", true, mktime(0, 0, 0, 1, 1, 2030));
                    setcookie("capcha", true, mktime(0, 0, 0, 1, 1, 2030));
                    header("Location: /new" . $newid . ".html/" . $pagenum . "/");
                } else {
                    $sm->assign("badCapcha", true);
                }
                $sm->assign("capcha", true);
                break;
        }
    }
}

//------------------------------------
//--выборка новости

$db->dbq("
            Select
                newid as newid,
                caption as caption,
                maintext as maintext,
                DATE_FORMAT(postdate, \"%d %M %Y, %H:%i\") as postdate,
                author as author,
                archiveid as archiveid,
                tags as tags,
                position as position
            From
                news
            Where
                newid = \"" . $newid . "\"
        ");

$new = $db->assoc();

$matches = array();
preg_match("'\[img=\"?([^\]]*)\"?\][\s]*(.*)[\s]*\[/img\]'iu", $new["maintext"], $matches);
$new["maintext"] = preg_replace("'\[img=\"?([^\]]*)\"?\][\s]*(.*)[\s]*\[/img\]'iu", "", $new["maintext"], 1);

$new["image"] = array();

if ($matches[1] == "preview") {
    $new["image"]["url"] = $matches[2];

    if ($matches[1] != "") {
        $type = exif_imagetype($curRealDir . $matches[2]);
        switch ($type) {
            case 1:
                $image = imagecreatefromgif($curRealDir . $matches[2]);
                $new["image"]["width"] = imagesx($image);
                $new["image"]["height"] = imagesy($image);
                imagedestroy($image);
                break;
            case 2:
                $image = imagecreatefromjpeg($curRealDir . $matches[2]);
                $new["image"]["width"] = imagesx($image);
                $new["image"]["height"] = imagesy($image);
                imagedestroy($image);
                break;
            case 3:
                $image = imagecreatefrompng($curRealDir . $matches[2]);
                $new["image"]["width"] = imagesx($image);
                $new["image"]["height"] = imagesy($image);
                imagedestroy($image);
                break;
            default:
                $new["image"]["width"] = 0;
                $new["image"]["height"] = 0;
                break;
        }
    }
}

$new["maintext"] = BBCodeToHtml($sm, $new["maintext"]);
$new["tags"] = json_decode($new["tags"], true);
$new = stripRecursive($new);

$sm->assign("new", $new);

//------------------------------------------------------
//---из админки
$COMMENTS_PER_PAGE = getOption($db, "COMMENTS_PER_PAGE");
//-----------------------

$db->dbq("
            Select
                Count(*)
            From
                comments
            Where
                newid = \"" . $newid . "\"
        ");
$arr = $db->row();
if ($arr[0] % $COMMENTS_PER_PAGE == 0) {
    $countPages = (int) ($arr[0] / $COMMENTS_PER_PAGE);
} else {
    $countPages = (int) ($arr[0] / $COMMENTS_PER_PAGE) + 1;
}
$sm->assign("countPages", $countPages);

$pagenum = trim(mysql_real_escape_string($_GET["pagenum"]));
if (!preg_match("'^[0-9]+$'iu", $pagenum) || $pagenum < 1 || $pagenum > $countPages) {
    $pagenum = 1;
}

$sm->assign("pagenum", $pagenum);

//--создаем массивы индексов для счетчика
//---из админки
$COMMENTS_COUNTER_LEFT = getOption($db, "COMMENTS_COUNTER_LEFT");
$COMMENTS_COUNTER_CENTER = getOption($db, "COMMENTS_COUNTER_CENTER");
$COMMENTS_COUNTER_RIGHT = getOption($db, "COMMENTS_COUNTER_RIGHT");
//-----------------------

$left = -(($pagenum - (int) ($COMMENTS_COUNTER_CENTER / 2) - 1) - $COMMENTS_COUNTER_LEFT);
$right = - $countPages + $COMMENTS_COUNTER_RIGHT + ($pagenum + (int) ($COMMENTS_COUNTER_CENTER / 2) + 1);

if ($left >= 0 && $right >= 0 && $countPages > 0) {
//--центральный массив сливается с левым
//--центральный массив сливается с правым
//--создаем только 1 массив
//--centerIndexes
    $centerIndexes = array();
    for ($i = 1; $i <= $countPages; $i++) {
        $centerIndexes[] = $i;
    }
    $sm->assign("centerIndexes", $centerIndexes);
//--------------------------------------
} elseif ($left >= 0 && $right < 0 && $countPages > 0) {
//--центральный массив сливается с левым
//--создаем только 2 массива
//--leftIndexes
//--rightIndexes
    $leftIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= ($COMMENTS_COUNTER_LEFT + $COMMENTS_COUNTER_CENTER); $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $countPages - $COMMENTS_COUNTER_RIGHT + 1; $i <= $countPages; $i++) {
        if ($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
} elseif ($left < 0 && $right >= 0 && $countPages > 0) {
//--центральный массив сливается с правым
//--создаем только 2 массива
//--leftIndexes
//--rightIndexes
    $leftIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= $COMMENTS_COUNTER_LEFT; $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $countPages - $COMMENTS_COUNTER_RIGHT - $COMMENTS_COUNTER_CENTER; $i <= $countPages; $i++) {
        if ($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
} elseif($countPages > 0) {
//--центральный массив ни с кем не сливается
//--создаем 3 массива
//--leftIndexes
//--centerIndexes
//--rightIndexes
    $leftIndexes = array();
    $centerIndexes = array();
    $rightIndexes = array();
    for ($i = 1; $i <= $COMMENTS_COUNTER_LEFT; $i++) {
        $leftIndexes[] = $i;
    }
    $endIndex = $i;
    for ($i = $pagenum - (int) ($COMMENTS_COUNTER_CENTER / 2); $i <= $pagenum + (int) ($COMMENTS_COUNTER_CENTER / 2); $i++) {
        if ($i > 0 && $i > $endIndex) {
            $centerIndexes[] = $i;
        }
    }
    $endIndex = $i;
    for ($i = $countPages - $COMMENTS_COUNTER_RIGHT + 1; $i <= $countPages; $i++) {
        if ($i > 0 && $i > $endIndex) {
            $rightIndexes[] = $i;
        }
    }
    $sm->assign("leftIndexes", $leftIndexes);
    $sm->assign("centerIndexes", $centerIndexes);
    $sm->assign("rightIndexes", $rightIndexes);
//---------------------------------------
}

$db->dbq("
            Select
                username as username,
                maintext as maintext,
                DATE_FORMAT(postdate, \"%d %M %Y, %H:%i\") as postdate
            From
                comments
            Where
                newid = \"" . $newid . "\"
            Order By
                postdate DESC
            Limit
                " . ($pagenum - 1) * $COMMENTS_PER_PAGE . ",
                " . $COMMENTS_PER_PAGE . "
        ");
$comments = array();
while ($arr = $db->assoc()) {
    $comments[] = stripRecursive($arr);
}

$sm->assign("comments", $comments);

$sm->assign("design", "http://" . DOMEN_NAME . "/" . $sm->template_dir);
$sm->assign("displayedHtml", "new.html");
$sm->display("new.html");
?>
